/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Common;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

/**
 *
 * @author KIENLT
 */
public class ConnectionDB {
    public static Connection ConnectDB(String post, String dbName, String userName, String pass) {
        Connection cnn = null;
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            cnn = DriverManager.getConnection("jdbc:sqlserver://localhost:"+post+";databaseName="+dbName, userName, pass);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "Connection Fail.", "Error", JOptionPane.ERROR_MESSAGE);
        }
        return cnn;
    }
    
    public static Connection ConnectionDatabase(){
        Connection cnn = null;
        FileReader fr = null;
        ArrayList arrData = new ArrayList();
        try {
            fr = new FileReader(FilePath.getFilePath());
            BufferedReader br = new BufferedReader(fr);
            String str = "";
            while((str = br.readLine()) != null){
                StringTokenizer st = new StringTokenizer(str, " ");
                while(st.hasMoreTokens()){
                    arrData.add(st.nextToken());
                }
            }
            cnn = ConnectDB(arrData.get(0).toString(), arrData.get(1).toString(), arrData.get(2).toString(), arrData.get(3).toString());
        } catch (Exception ex) {
            
        }
        return cnn;
    }
    
    public static boolean CloseDB(Object obj) throws Exception{
        if(obj  instanceof Connection){
            ((Connection)obj).close();
            return true;
        }
        if(obj instanceof Statement){
            ((Statement)obj).close();
            return true;
        }
        if(obj instanceof ResultSet){
            ((ResultSet)obj).close();
            return true;
        }
        if(obj instanceof PreparedStatement){
            ((PreparedStatement)obj).close();
            return true;
        }
        return false;
    }
}
